<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 左侧图片展示 -->
      <div class="login-banner">
        <img src="@/assets/images/user/cover.png" alt="美食展示" class="banner-image">
        <div class="banner-overlay">
          <h2>美食之旅，从这里开始</h2>
          <p>万千美食，一键即达</p>
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <div class="login-form">
        <h1 class="form-title">欢迎登录</h1>
        <p class="form-subtitle">请使用手机号登录系统</p>

        <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="demo-ruleForm"
            @keyup.enter="handleLogin"
        >
          <el-form-item prop="phone">
            <el-input
                v-model="loginForm.phone"
                placeholder="请输入手机号"
                class="input-with-select"
                clearable
                maxlength="11"
            >
              <template #prepend>
                <el-select v-model="areaCode" placeholder="+86" style="width: 80px">
                  <el-option label="+86" value="+86" />
                  <el-option label="+852" value="+852" />
                  <el-option label="+853" value="+853" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="code">
            <div class="code-input">
              <el-input
                  v-model="loginForm.code"
                  placeholder="请输入验证码"
                  style="width: 60%"
              />
              <el-button
                  :disabled="!canGetCode || countdown > 0"
                  @click="getSmsCode"
                  style="width: 38%; margin-left: 2%"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                class="login-btn"
                :loading="loading"
                @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <div class="form-footer">
          <el-checkbox v-model="agreeProtocol">我已阅读并同意</el-checkbox>
          <el-link type="primary" :underline="false">《用户协议》</el-link>
          <el-link type="primary" :underline="false">《隐私政策》</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import {login, sendMsg} from "@/api/user";
import {setUserRole} from "@/utils/auth";

const router = useRouter()

// 表单数据
const loginForm = ref({
  phone: '',
  code: ''
})

// 区号选择
const areaCode = ref('+86')

// 验证码倒计时
const countdown = ref(0)
let timer = null

// 加载状态
const loading = ref(false)

// 协议勾选
const agreeProtocol = ref(false)

// 表单验证规则
const loginRules = {
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {
      pattern: /^\d{4}$/,
      message: '验证码为4位数字',
      trigger: 'blur'
    }
  ]
}

// 是否可以获取验证码
const canGetCode = computed(() => {
  return /^1[3-9]\d{9}$/.test(loginForm.value.phone)
})

// 获取验证码
const getSmsCode = async () => {
  if (!canGetCode.value) {
    ElMessage.warning('请输入正确的手机号')
    return
  }
  const submitFormData = {
    phone: loginForm.value.phone
  }
  // 模拟发送验证码
  const res = await sendMsg(submitFormData)
  if(res.code === '200') {
    ElMessage.success('验证码已发送')
  }else {
    ElMessage.error(res.msg);
  }
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const loginFormRef = ref(null)
// 处理登录
const handleLogin = async () => {

  if (!agreeProtocol.value) {
    ElMessage.warning('请先阅读并同意用户协议和隐私政策')
    return
  }
  try {
    // 验证表单
    await loginFormRef.value.validate()

    loading.value = true
    // MD5加密密码
    const params = {
      ...loginForm.value,
    }

    const res = await login(params)
    if (res.code === "200") {
      ElMessage.success('登录成功')
      localStorage.setItem('token', res.data)
      setUserRole('user')
      await router.push({name: 'HomePage'})
    } else {
      ElMessage.error(res.msg || '登录失败')
    }
  } catch (error) {
    if (error.response) {
      const msg = error.response.data.msg || '登录失败'
      ElMessage.error(msg)
    } else {
      ElMessage.error('请求失败，请检查网络')
    }
  } finally {
    loading.value = false
  }
  await new Promise(resolve => setTimeout(resolve, 300)) // 模拟延迟
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  background: url('@/assets/images/user/background.jpg') no-repeat center center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 1;
}

.login-wrapper {
  position: relative;
  z-index: 2;
  width: 80%;
  max-width: 1000px;
  height: 600px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
}

.login-banner {
  width: 50%;
  height: 100%;
  position: relative;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30px;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: #fff;
}

.banner-overlay h2 {
  font-size: 28px;
  margin-bottom: 10px;
}

.banner-overlay p {
  font-size: 16px;
  opacity: 0.9;
}

.login-form {
  width: 50%;
  padding: 60px 50px;
  display: flex;
  flex-direction: column;
}

.form-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.form-subtitle {
  font-size: 14px;
  color: #999;
  margin-bottom: 40px;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  margin-top: 20px;
}

.form-footer {
  margin-top: auto;
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.form-footer .el-link {
  margin-left: 5px;
}

.code-input {
  display: flex;
  justify-content: space-between;
}

@media (max-width: 768px) {
  .login-wrapper {
    flex-direction: column;
    height: auto;
  }

  .login-banner, .login-form {
    width: 100%;
  }

  .login-banner {
    height: 200px;
  }
}
</style>